package org.misty.practices.algorithm.levenshtein;

/**
 * @author Misty on 2021-08-07
 * <p>
 * 字符串相似算法
 * Levenshtein Distance 算法，又叫 Edit Distance 算法，是指两个字符串之间，由一个转成另一个所需的最少编辑操作次数。
 * 许可的编辑操作包括将一个字符替换成另一个字符，插入一个字符，删除一个字符。一般来说，编辑距离越小，两个串的相似度越大。
 * https://www.cnblogs.com/xiaoyulong/p/8846745.html
 */
public class LevenshteinDistance {
    public static double levenshtein(String str1, String str2) {
        char[] chars1 = str1.toCharArray();
        char[] chars2 = str2.toCharArray();

        int len1 = chars1.length;
        int len2 = chars2.length;

        int[][] dif = new int[len1 + 1][len2 + 1];

        for (int i = 0; i <= len1; i++) {
            dif[i][0] = i;
        }
        for (int i = 0; i <= len2; i++) {
            dif[0][i] = i;
        }

        int temp;
        for (int i = 1; i <= len1; i++) {
            for (int j = 1; j <= len2; j++) {
                if (chars1[i - 1] == chars2[j - 1]) {
                    temp = 0;
                } else {
                    temp = 1;
                }

                dif[i][j] = min(dif[i - 1][j - 1] + temp, dif[i][j - 1] + 1, dif[i - 1][j] + 1);
            }
        }
        return 1 - 1.0 * dif[len1][len2] / Math.max(len1, len2);
    }

    private static int min(int... nums) {
        int min = Integer.MAX_VALUE;
        for (int num : nums) {
            if (min > num) {
                min = num;
            }
        }
        return min;
    }

    public static void sample(String s1, String s2) {
        System.out.printf("%s cmp %s is %f\n", s1, s2, levenshtein(s1, s2));
    }

    public static void main(String[] args) {
        sample("abc", "abc");
        sample("abc", "bcd");
        sample("a", "bc");
        sample("abcabc", "abcdabc");
    }
}
